package bean;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;

import dao.JPA;
import dao.TreatmentActDAO;
import dao.TreatmentRequestDAO;
import entity.TreatmentAct;

@ManagedBean
@ViewScoped
public class ViewTreatmentActBean {

	@Inject @JPA
	private TreatmentActDAO treatmentActDAO;
	@Inject @JPA
	private TreatmentRequestDAO treatmentRequestDAO;
	private TreatmentAct treatmentAct = new TreatmentAct();
	private int reqId;
	
	@PostConstruct
	private void init() {
		FacesContext context = FacesContext.getCurrentInstance();
		Map<String, String> params = context.getExternalContext().getRequestParameterMap();		
		treatmentAct = treatmentActDAO.getEntityById(Integer.valueOf(params.get("actId")));	
		if(params.get("reqId") != null)
			reqId = Integer.valueOf(params.get("reqId"));
	}
	
	public String getInvolvedDoctors() {
		List<String> doctorList = treatmentRequestDAO.selectDoctorsNamesByActId(treatmentAct.getId());
		if(doctorList.size() > 0) {
			String res = doctorList.toString();
			res = res.substring(1, res.length()-1);
			return res;
		} else return "None";
	}
	
	public void updateAct() {
		treatmentActDAO.merge(treatmentAct);
		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Act updated", "Act updated"));
	}
	
	public void deleteAct() {
		treatmentActDAO.remove(treatmentAct);
		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Act deleted", "Act deleted"));
		goBack();
	}
	
	public void goBack() {		
		try {
			if(reqId == 0)
				FacesContext.getCurrentInstance().getExternalContext().redirect("viewTreatmentHistory.xhtml?clientId=" + treatmentAct.getClient().getId());
			else
				FacesContext.getCurrentInstance().getExternalContext().redirect("../doc/viewTreatmentRequest.xhtml?reqId=" + reqId);			
		} catch(IOException ioe) {
			ioe.printStackTrace();
		}
	}
	
	public TreatmentAct getTreatmentAct() {
		return treatmentAct;
	}
	
}
